from flask import Flask, request, jsonify, render_template
import pymysql
from pymysql.cursors import DictCursor

app = Flask(__name__)

# 数据库配置
DB_CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': 'root',
    'db': 'testdb',  # 请替换为实际数据库名称
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['POST'])
def login():
    # 获取请求数据
    data = request.get_json() or request.form
    username = data.get('username')
    password = data.get('password')
    
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
    
    try:
        # 连接数据库
        connection = pymysql.connect(**DB_CONFIG)
        with connection.cursor() as cursor:
            # 查询用户
            sql = "SELECT * FROM users WHERE username = %s AND password = %s"
            cursor.execute(sql, (username, password))
            user = cursor.fetchone()
            
            if user:
                return jsonify({'success': True, 'message': '登录成功', 'user': user})
            else:
                return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
    except pymysql.MySQLError as e:
        return jsonify({'success': False, 'message': f'数据库错误: {str(e)}'}), 500
    finally:
        if connection:
            connection.close()

@app.route('/success')
def success():
    return render_template('success.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True)